#
# "@(#) $Id: Importer.py,v 1.1.1.1 2006-07-27 03:16:08 gioshe Exp $"
#
# This work is released under the GNU GPL, version 2 or later.
#
from qt import *
import string, os, time, re
from Utils.Settings import *

class ImporterEvent(QCustomEvent):
	def __init__(self,status = None):
		QCustomEvent.__init__(self,QEvent.User+4)
		self._status = status
	
	def status(self):
		return self._status

class ImporterThread(QThread):
	def __init__(self,filePath,library,playlist,index,count,managed):
		QThread.__init__(self)
		self.fullPath = filePath
		self.managed = managed
		self.library = library
		self.playlist = playlist
		self.index = index
		self.total = count

	def run(self):
		self.importFile()

	def importFile(self):
		#print "importing",self.fullPath
		(srcPath,fileName) = os.path.split(self.fullPath)
		track = self.library.trackForFilePath(self.fullPath)
		if track!=None:
			self.emitEvent({'Source':'Importer','Status':'Importing','Filename':fileName,'currentTime':self.index,'totalTime':self.total})
			if type(self.fullPath).__name__=='unicode':
				self.fullPath = self.fullPath.encode('latin-1')
			track.setFile(self.fullPath)
			track.originalLocation = self.fullPath
			track.managed = self.managed
			self.emitEvent({'Source':'Importer','Status':'Imported','Track':track,'currentTime':self.index,'totalTime':self.total,'Library':self.library,'Playlist':self.playlist})

	def emitEvent(self,status):
		event = ImporterEvent(status)
		QApplication.postEvent(Importer.singleton(),event)


def bumpUI():
	from LApplication import LApplication
	app = LApplication.singleton()
	if app:
		app.lock()
		app.processEvents()
		app.unlock()

class Importer(QObject):
	def __init__(self):
		QObject.__init__(self)
		self.tracksToImport = []
		self.thread = None
		self.altThread = None
		self.mutex = QMutex()
		self.index = 0
		self.count = 0
		self.timer = QTimer()
		QObject.connect(self.timer,SIGNAL('timeout()'),self.importNextTrack)
		self.importCount=0
	
	def customEvent(self,e):
		self.gotStatus(e.status())
	
	def gotStatus(self,status):
		state = status['Status']
		#print status
		if state=='Imported':
			track = status['Track']
			library = status['Library']
			if len(self.tracksToImport)==0:
				library.importsComplete = True
			playlist = status['Playlist']
			trackInfo = status.get('TrackInfo',None)
			
			if (self.importCount > 100 or state=='End'):
				self.importCount=0
				#self.emit(PYSIGNAL("bulkEditEnd"),(self,None))
				library.finishImportFile(track,playlist,trackInfo)
				#self.emit(PYSIGNAL("bulkEditBegin"),(self,None))
				#print "DONE::",track
			else:	
				self.importCount+=1
				library.finishImportFile(track,playlist,trackInfo)
				#print "GOING::",track
		#elif state=="End":
			#self.emit(PYSIGNAL("bulkEditEnd"),(self,None))
		self.emit(PYSIGNAL('status'),(status,None))
	
	def importFiles(self,uris,library,playlist=None,managed = None):
		#self.emit(PYSIGNAL("bulkEditBegin"),(self,None))
		if managed==None:
			managed = Settings.settings().get('Managed',False)
		if uris and len(uris)>0:
			if len(self.tracksToImport)==0:
				self.gotStatus({'Source':'Importer','Status':'Begin'})
				self.index = 0
				self.count = 0
			self.count = self.count+len(uris)
			for uri in uris:
				if type(uri)==dict:
					self.tracksToImport.append({'URI':uri['URI'],'Library':library, 'Playlist':playlist, 'TrackInfo':uri['TrackInfo'],'Managed':managed})
				else:
					self.tracksToImport.append({'URI':uri,'Library':library,'Playlist':playlist,'Managed':managed})
			self.timer.stop()
			self.timer.start(100)
	
	def importNextTrack(self):
		if self.thread and not self.thread.finished():
			return
		try: self.thread = None
		except: pass
		if len(self.tracksToImport)==0:
			self.timer.stop()
			self.gotStatus({'Source':'Importer','Status':'End'})
		else:
			trackInfo = self.tracksToImport[0]
			self.tracksToImport = self.tracksToImport[1:]
			self.thread = ImporterThread(trackInfo['URI'],trackInfo['Library'],trackInfo['Playlist'],self.index,self.count,trackInfo['Managed'])
			self.thread.start()
			self.altThread = self.thread
			self.index = self.index+1
				
	def kill(self):
		self.timer.stop()
		self.tracksToImport = []
		if self.thread and not self.thread.finished():
			t = long(time.time())+10
			while t>=long(time.time()):
				bumpUI()
				time.sleep(0.1)
				if self.thread.finished():
					break
			if self.thread and not self.thread.finished():
				self.thread.terminate()
				if not self.thread.wait(2000):
					self.thread = None
				self.thread = None
			self.gotStatus({'Source':'Importer','Status':'End'})
		self.thread = None
		self.altThread = None
	
	def static_killCurrentImporter():
		Importer.singleton().kill()
	killCurrentImporter = staticmethod(static_killCurrentImporter)

	def static_singleton():
		global _importerSingleton
		return _importerSingleton

	singleton = staticmethod(static_singleton)

_importerSingleton = Importer()
